package com.changan.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.changan.condition.UserRegisterCondition;
import com.changan.config.EmailConfig;
import com.changan.exception.BusinessException;
import com.changan.response.ResultCode;
import com.changan.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changan.entity.User;
import com.changan.mapper.UserMapper;
import com.changan.service.UserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Value(value = "${email.send.enable}")
    private boolean enableSendEmail;

    String activeCodeKeyPre = "active:";

    @Autowired
    private EmailService emailService;

    @Autowired
    private EmailConfig emailConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional
    public boolean userRegister(UserRegisterCondition condition) {
        //先判断用户的user_code是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserCode, condition.getUserCode());
        User u = this.baseMapper.selectOne(queryWrapper);
        if (u != null) {
            //用户存在则抛出异常
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        //如果不存在，则实现注册
        condition.setUserPassword(SecureUtil.md5(condition.getUserPassword()));
        //创建一个注册用户
        User user = new User();
        //实现数据的复制
        BeanUtils.copyProperties(condition, user);
        //初始化其他数据，指定用户类型（默认为自动注册用户）
        //user.setUserType(SystemConstants.REGISTRATION);
        this.save(user);
        //生成验证码
        //通过huTool生成6位数的随机数
        String activationCode = RandomUtil.randomNumbers(6);
        log.info("激活码：{}", activationCode);
        //发送邮件
        if (enableSendEmail) {
            emailService.sendStringEmail("2502598599@qq.com", "爱旅行注册验证码", activationCode);
        }
        //4、激活码存入Redis中 过期时间为 30 分钟
        stringRedisTemplate.opsForValue().set(activeCodeKeyPre +
                user.getUserCode(), activationCode, 30, TimeUnit.MINUTES);
        return true;
    }
}
